package com.xpu.cos.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xpu.cos.entity.User;
import com.xpu.cos.result.Result;
import com.xpu.cos.service.UserService;
import com.xpu.cos.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cos/index")
public class IndexController {
      @Autowired
    private UserService userService;

      @PostMapping("register")
    public Result register(@RequestBody User user) throws Exception {
          //String username = user.getUsername();
          Boolean exist = userService.getUserByUsername(user);
          if (exist){
              return userService.addUser(user);

          }else {
              return Result.fail("用户名已存在！");
          }
      }
    @PostMapping("login")
    public Result login(@RequestBody User user) throws Exception {
        String username = user.getUsername();
        String password = user.getPassword();
        User userTemp = userService.login(username, password);
        if(userTemp!=null){
            String token = TokenUtils.createToken(String.valueOf(userTemp.getId()), userTemp.getPassword());//生成token
            userTemp.setToken(token);
            return Result.ok(userTemp);
        } else return Result.fail("用户不存在！");
    }
}
